#include "head.h"

int main(int argc, char *argv[])
{
    // ./client 192.168.118.128 1234
    ARGS_CHECK(argc,3);

    int sockfd = socket(AF_INET,SOCK_STREAM,0);
    ERROR_CHECK(sockfd,-1,"socket");

    struct sockaddr_in serverAddr;
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(atoi(argv[2]));
    serverAddr.sin_addr.s_addr = inet_addr(argv[1]);
    int ret = connect(sockfd,(struct sockaddr *)&serverAddr, sizeof(serverAddr));
    ERROR_CHECK(ret,-1,"connect");

    int epfd = epoll_create(1);
    ERROR_CHECK(epfd,-1,"epoll_create");
    epollAdd(epfd,STDIN_FILENO);
    epollAdd(epfd,sockfd);

    printf("Please enter your username: "); 
    fflush(stdout);
    char username[256];
    scanf("%s",username);
    train_t train;
    train.length = strlen(username);
    strcpy(train.data,username);
    send(sockfd,&train,sizeof(int)+train.length,MSG_NOSIGNAL);

    int length;
    char pwd[256] = {0};
    recv(sockfd,&length,sizeof(int),MSG_WAITALL);
    recv(sockfd,pwd,length,MSG_WAITALL);
    printf("%s\n",pwd);

    int orderflag;
    struct epoll_event readySet[5];
    while(1)
    {
        printf("> ");
        fflush(stdout);

        int readyNum = epoll_wait(epfd,readySet,5,-1);
        for(int i = 0; i < readyNum; ++i)
        {//客户端输入了命令
            if(readySet[i].data.fd == STDIN_FILENO)
            {
                char buf[1024];
                ssize_t sret = read(STDIN_FILENO,buf,sizeof(buf));
                buf[sret] = '\0';
                //解析命令
                char args[256];
                int ret = whichOrder(buf,&orderflag,args);
                if(ret == 0)
                {
                    //命令合法，发送请求给服务端
                    transOrder(sockfd,orderflag,args);
                }
            }
            else
            {//服务端发送了消息
                //to do 
                switch(orderflag)
                {

                }
            }
        }
    }

    close(sockfd);

    return 0;
}
